package com.qf.xiaomi.service.impl;

import com.qf.xiaomi.dao.AddressDao;
import com.qf.xiaomi.dao.impl.AddressDaoImpl;
import com.qf.xiaomi.pojo.Address;
import com.qf.xiaomi.service.AddressService;
import com.qf.xiaomi.utils.DataSourceUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * ThreadLocal
 * @author 千锋教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
public class AddressServiceImpl implements AddressService {

    AddressDao dao = new AddressDaoImpl();

    @Override
    public List<Address> getAddrList(int uid) {
        return dao.getAddList(uid);
    }

    @Override
    public void addAddress(Address address) {
        dao.addAddress(address);
    }

    @Override
    public void deleteById(int id) {
        dao.delete(id);
    }

    @Override
    public void updateAddress(Address address) {
        dao.update(address);
    }

    /**
     * 设置默认收货地址
     *
     *  1. 设置该用户的 所有收货地址都是 普通的
     *  2. 设置该用户的 某收货地址为默认收货地址
     * @param uid
     * @param aId
     */
    @Override
    public void setDefaultAddress(int uid, String aId) {
        Connection conn = DataSourceUtils.getConnection();
        try {
            //设置为不能自动提交
            conn.setAutoCommit(false);
            //把所有的收货地址都设置为 普通的
            dao.set2Normal(uid);
            //设置某收货地址为 默认收货地址
            dao.setDefaultAddress(aId);
            //提交事务
            conn.commit();
        }catch (Exception e ){
            e.printStackTrace();
            //回滚事务
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }

    }
}
